<?php

namespace app\index\middleware;

use app\model\ArticleModel;
use app\model\CategoryModel;
use think\facade\Request;
use think\facade\View;
use think\Response;

class Category
{
    public function handle($request, \Closure $next)
    {
        $categoryList = CategoryModel::select();

        $path = Request::pathinfo();
        preg_match("/\/category_id\/(\d+)\//i", $path, $matches);
        $currentCategoryId = $matches[1] ?? '0';

        preg_match("/\/article_id\/(\d+)\//i", $path, $matches);
        $articleId = $matches[1] ?? '0';
        if ($articleId) {
            $article = ArticleModel::find($articleId);
            $currentCategoryId = $article['category_id'];
        }


        View::assign('categoryList', $categoryList);
        View::assign('currentCategoryId', $currentCategoryId);

        $response = $next($request);
        return $response;
    }

    public function end(Response $response)
    {

    }
}